﻿//-------------------------------------------------------------------------------------
// All Rights Reserved , Copyright (C) 2011 , DotNet, Ltd.
//-------------------------------------------------------------------------------------

using System;
using System.Data;
using System.Windows.Forms;

namespace DotNet.WinForm.User
{
    using DotNet.Model;
    using DotNet.Service;
    using DotNet.Utilities;
    using DotNet.WinForm.Utilities;

    /// <summary>
    /// FrmUserAdd
    /// 添加用户（帐户）。
    ///
    /// 修改纪录
    ///
    ///     2010.09.16 版本：1.3 DotNet 仔细整理代码一次。
    ///     2010.04.06 版本：1.2 DotNet 修改为面向实体。
    ///     2008.04.05 版本：1.1 DotNet 整理调试程序。
    ///     2007.07.03 版本：1.0 DotNet 主键编辑。
    ///
    /// 版本：1.3
    ///
    /// <author>
    ///		<name>DotNet</name>
    ///		<date>2010.09.16</date>
    /// </author>
    public partial class FrmUserAdd : BaseForm
    {
        public FrmUserAdd()
        {
            InitializeComponent();
        }

        #region public override void SetHelp() 设置帮助信息

        /// <summary>
        /// 设置帮助信息
        /// </summary>
        public override void SetHelp()
        {
            this.HelpButton = true;
            this.helpProvider.HelpNamespace = BaseSystemInfo.HelpNamespace;
            this.helpProvider.SetHelpString(this.lblUserName, "在此处键入用户名（建议用英文）。");
            this.helpProvider.SetHelpString(this.lblFullName, "在此处键入全称（建议用中文）。");
            this.helpProvider.SetHelpString(this.lblCode, "在此处键入用户编号（建议用数字）。");
            this.helpProvider.SetHelpString(this.lblDefaultRole, "在此处选择类型。");
            this.helpProvider.SetHelpString(this.lblPassword, "在此处键入密码。");
            this.helpProvider.SetHelpString(this.lblConfirmPassword, "在此处键入确认密码。");
        }

        #endregion public override void SetHelp() 设置帮助信息

        #region private void GetRoles() 获得角色列表

        /// <summary>
        /// 获得角色列表
        /// </summary>
        private void GetRoles()
        {
            // 绑定类型数据
            DataTable dataTable = ServiceManager.Instance.UserService.GetRoleDT(this.UserInfo);
            DataRow dataRow = dataTable.NewRow();
            dataTable.Rows.InsertAt(dataRow, 0);
            this.cmbDefaultRole.DisplayMember = BaseRoleTable.FieldRealName;
            this.cmbDefaultRole.ValueMember = BaseRoleTable.FieldId;
            this.cmbDefaultRole.DataViewSource = dataTable.DefaultView;
        }

        #endregion private void GetRoles() 获得角色列表

        #region public override void SetControlState() 按钮的状态设置

        /// <summary>
        /// 按钮的状态设置
        /// </summary>
        public override void SetControlState()
        {
            if (BaseSystemInfo.AllowNullPassword)
            {
                this.lblConfirmPasswordReq.Visible = false;
                this.lblPasswordReq.Visible = false;
            }
        }

        #endregion public override void SetControlState() 按钮的状态设置

        #region public override void FormOnLoad() 加载窗体

        /// <summary>
        /// 加载窗体
        /// </summary>
        public override void FormOnLoad()
        {
            // 获得角色列表
            this.GetRoles();
        }

        #endregion public override void FormOnLoad() 加载窗体

        #region public override bool CheckInput() 检查输入的有效性

        /// <summary>
        /// 检查输入的有效性
        /// </summary>
        /// <returns>有效</returns>
        public override bool CheckInput()
        {
            bool returnValue = true;
            this.txtUserName.Text = this.txtUserName.Text.TrimEnd();
            if (this.txtUserName.Text.Trim().Length == 0)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(AppMessage.Format(AppMessage.MSG0007, AppMessage.MSG9978), AppMessage.MSG0000, MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.txtUserName.Focus();
                return false;
            }
            this.txtFullName.Text = this.txtFullName.Text.TrimEnd();
            if (this.txtFullName.Text.Trim().Length == 0)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(AppMessage.Format(AppMessage.MSG0007, AppMessage.MSG9978), AppMessage.MSG0000, MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.txtFullName.Focus();
                return false;
            }

            // 密码不能为空
            if (!BaseSystemInfo.AllowNullPassword)
            {
                if (this.txtPassword.Text.Trim().Length == 0)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show(AppMessage.Format(AppMessage.MSG0007, AppMessage.MSG9964), AppMessage.MSG0000, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.txtPassword.Focus();
                    return false;
                }
            }
            if (!this.txtConfirmPassword.Text.Equals(this.txtPassword.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(AppMessage.MSG9967, AppMessage.MSG0000, MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.txtPassword.Clear();
                this.txtConfirmPassword.Clear();
                this.txtPassword.Focus();
                return false;
            }
            return returnValue;
        }

        #endregion public override bool CheckInput() 检查输入的有效性

        #region public override bool SaveEntity() 保存

        /// <summary>
        /// 保存
        /// </summary>
        /// <returns>成功</returns>
        public override bool SaveEntity()
        {
            bool returnValue = false;
            string statusCode = string.Empty;
            string statusMessage = string.Empty;

            // 转换数据
            BaseUserEntity userEntity = new BaseUserEntity();
            userEntity.UserName = this.txtUserName.Text;
            userEntity.RealName = this.txtFullName.Text;
            userEntity.Code = this.txtCode.Text;
            int roleId = 0;
            if (this.cmbDefaultRole.SelectedValue != null && this.cmbDefaultRole.SelectedValue.ToString().Length > 0)
            {
                int.TryParse(this.cmbDefaultRole.SelectedValue.ToString(), out roleId);
                userEntity.RoleId = roleId;
            }
            else
            {
                userEntity.RoleId = null;
            }
            userEntity.UserPassword = this.txtPassword.Text;

            // 是否进行分级管理
            if (BaseSystemInfo.UsePermissionScope)
            {
                userEntity.CompanyName = UserInfo.CompanyFullName;
                userEntity.DepartmentName = UserInfo.DepartmentFullName;
                userEntity.WorkgroupName = UserInfo.WorkgroupFullName;
            }
            userEntity.Enabled = this.chbEnabled.Checked ? 1 : 0;
            this.EntityId = ServiceManager.Instance.UserService.AddUser(UserInfo, userEntity, out statusCode, out statusMessage);
            if (statusCode == StatusCode.OKAdd.ToString())
            {
                if (BaseSystemInfo.ShowInformation)
                {
                    // 添加成功，进行提示
                    DevExpress.XtraEditors.XtraMessageBox.Show(statusMessage, AppMessage.MSG0000, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                this.DialogResult = DialogResult.OK;
                returnValue = true;
            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(statusMessage, AppMessage.MSG0000, MessageBoxButtons.OK, MessageBoxIcon.Information);
                if (statusCode == StatusCode.ErrorUserExist.ToString())
                {
                    this.txtUserName.SelectAll();
                    this.txtUserName.Focus();
                }

                // 是否编号重复了，提高友善性
                if (statusCode == StatusCode.ErrorCodeExist.ToString())
                {
                    this.txtCode.SelectAll();
                    this.txtCode.Focus();
                }
                return false;
            }

            // 设置鼠标默认状态
            this.Cursor = Cursors.Default;
            return returnValue;
        }

        #endregion public override bool SaveEntity() 保存

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (this.CheckInput())
            {
                // 设置鼠标繁忙状态
                this.Cursor = Cursors.WaitCursor;
                try
                {
                    if (this.SaveEntity())
                    {
                        // 关闭窗口
                        this.Close();
                    }
                }
                catch (Exception ex)
                {
                    this.ProcessException(ex);
                }
                finally
                {
                    // 设置鼠标默认状态
                    this.Cursor = Cursors.Default;
                }
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}